package cn.demoxy.handler;

import cn.demoxy.exception.DemoException;
import cn.demoxy.result.R;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static cn.demoxy.enums.ExceptionMessageEnum.NO_LOGIN;
import static cn.demoxy.enums.ExceptionMessageEnum.NO_PERMISSION;

/**
 * @auther demo
 * @date 2022/5/17 10:58
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 认证异常拦截处理返回响应结果
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseBody
    public R error(UnauthenticatedException e) {
        e.printStackTrace();
        return R.build(NO_LOGIN);
    }

    /**
     * 授权异常拦截处理返回响应结果
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public R error(AuthorizationException e) {
        e.printStackTrace();
        return R.build(NO_PERMISSION);
    }

    /**
     * 自定义异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DemoException.class)
    @ResponseBody
    public R error(DemoException e) {
        return R.build(e.getCode(), e.getMessage());
    }
}
